package club.gskj.gulimall.product.service.impl;

import club.gskj.common.utils.R;
import club.gskj.gulimall.product.entity.SkuImagesEntity;
import club.gskj.gulimall.product.entity.SpuInfoDescEntity;
import club.gskj.gulimall.product.entity.SpuInfoEntity;
import club.gskj.gulimall.product.feign.SeckillFeignService;
import club.gskj.gulimall.product.service.*;
import club.gskj.gulimall.product.vo.SeckillSkuInfoVO;
import club.gskj.gulimall.product.vo.SkuItemSaleAttrVo;
import club.gskj.gulimall.product.vo.SkuItemVo;
import club.gskj.gulimall.product.vo.SpuItemAttrGroupVo;
import com.alibaba.fastjson.TypeReference;
import io.reactivex.Completable;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ThreadPoolExecutor;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import club.gskj.common.utils.PageUtils;
import club.gskj.common.utils.Query;

import club.gskj.gulimall.product.dao.SkuInfoDao;
import club.gskj.gulimall.product.entity.SkuInfoEntity;
import org.springframework.util.StringUtils;

import javax.swing.*;


@Service("skuInfoService")
public class SkuInfoServiceImpl extends ServiceImpl<SkuInfoDao, SkuInfoEntity> implements SkuInfoService {


    @Autowired
    private SkuImagesService skuImagesService;

    @Autowired
    private SpuInfoDescService spuInfoDescService;

    @Autowired
    private SpuInfoService spuInfoService;

    @Autowired
    private AttrGroupService attrGroupService;

    @Autowired
    private SkuSaleAttrValueService skuSaleAttrValueService;

    @Autowired
    private SkuInfoService skuInfoService;

    @Autowired
    private SeckillFeignService seckillFeignService;

    /**
     * 自定义线程池
     */
    @Autowired
    private ThreadPoolExecutor threadPoolExecutor;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<SkuInfoEntity> page = this.page(
                new Query<SkuInfoEntity>().getPage(params),
                new QueryWrapper<SkuInfoEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public void saveSkuInfo(SkuInfoEntity skuInfoEntity) {
        this.save(skuInfoEntity);
    }

    @Override
    public PageUtils queryPageByCondition(Map<String, Object> params) {

        /* 封装查询条件
            key:
            catelogId: 0
            brandId: 0
            min: 0
            max: 0
         */
        QueryWrapper<SkuInfoEntity> wrapper = new QueryWrapper<>();

        // 关键词查询
        String key = (String) params.get("key");
        if (!StringUtils.isEmpty(key)) {
            wrapper.and((w) -> {
                w.eq("sku_id", key)
                        .or().like("sku_name", key);
            });
        }

        // 分类查询
        String catelogId = (String) params.get("catelogId");
        if (!StringUtils.isEmpty(catelogId) && !"0".equals(catelogId)) {
            wrapper.eq("catalog_id", catelogId);
        }
        // 品牌查询
        String brandId = (String) params.get("brandId");
        if (!StringUtils.isEmpty(brandId) && !"0".equals(brandId)) {
            wrapper.eq("brand_id", brandId);
        }
        String min = (String) params.get("min");
        if (!StringUtils.isEmpty(min)) {
            wrapper.ge("price", min);
        }
        String max = (String) params.get("max");

        if (!StringUtils.isEmpty(max)) {
            try {
                // 判断max最大值是否大于0
                BigDecimal maxBigDecimal = new BigDecimal(max);
                if (maxBigDecimal.compareTo(new BigDecimal("0")) == 1) {
                    wrapper.le("price", max);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        IPage<SkuInfoEntity> page = this.page(new Query<SkuInfoEntity>().getPage(params), wrapper);
        return new PageUtils(page);
    }

    @Override
    public List<SkuInfoEntity> listSkuBySpuId(Long spuId) {
        return this.list(new QueryWrapper<SkuInfoEntity>().eq("spu_id", spuId));
    }

    /**
     * @param skuId
     * @return club.gskj.gulimall.product.vo.SkuItemVo
     * @author 康纳-connor
     * @creed: Talk is cheap,show me the code
     * @date 21.3.14 13:59
     * @Description 通过skuid 获取页面中对应的属性信息，使用异步任务编排模式，加快程序响应速度，增加系统吞吐量
     */
    @Override
    public SkuItemVo item(Long skuId) throws ExecutionException, InterruptedException {
        SkuItemVo skuItemVo = new SkuItemVo();

        // 使用异步任务编程，异步执行所有任务，加快程序响应速度,系统吞吐量

        // 1.异步获取sku基本信息
        CompletableFuture<SkuInfoEntity> info = CompletableFuture.supplyAsync(() -> {
            // skuinfo基本信息
            SkuInfoEntity infoEntity = this.getById(skuId);
            skuItemVo.setInfo(infoEntity);
            return infoEntity;
        }, threadPoolExecutor);

        // 2.基本信息任务执行完后，继续调用异步任务，并获取上一次任务返回值，继续操作
        CompletableFuture<Void> saleAttrFuture = info.thenAcceptAsync((res) -> {
            // res 为上一次任务的返回值，这里作为参数传入，继续使用
            // spu销售属性组合
            List<SkuItemSaleAttrVo> saleAttrVos = skuSaleAttrValueService.listSaleAttrsBySpuId(res.getSpuId());
            skuItemVo.setSaleAttrs(saleAttrVos);
        }, threadPoolExecutor);

        // 2.基本信息任务执行完后，继续调用异步任务，并获取上一次任务返回值，继续操作
        CompletableFuture<Void> spuInfoDescFuture = info.thenAcceptAsync((res) -> {
            // 获取spu介绍
            SpuInfoDescEntity spuInfoDescEntity = spuInfoDescService.getById(res.getSpuId());
            skuItemVo.setDesp(spuInfoDescEntity);
        }, threadPoolExecutor);

        // 2.基本信息任务执行完后，继续调用异步任务，并获取上一次任务返回值，继续操作
        CompletableFuture<Void> groupAttrsFuture = info.thenAcceptAsync((res) -> {
            // 三级分类id
            Long catelogId = res.getCatelogId();
            // 获取sku中对应的spuid
            Long spuId = res.getSpuId();

            // 获取spu的规则参数信息
            List<SpuItemAttrGroupVo> groupAttrs = attrGroupService.listAttrGroupWithAttrsBySpuId(spuId, catelogId);
            skuItemVo.setGroupAttrs(groupAttrs);
        }, threadPoolExecutor);

        // 获取skuinfo 图片信息任务，不依赖其他异步任务返回结果，直接重新开启任务执行即可。
        CompletableFuture<Void> imageFuture = CompletableFuture.runAsync(() -> {
            //skuinfo 图片信息
            List<SkuImagesEntity> images = skuImagesService.getImagesBySkuId(skuId);
            skuItemVo.setImages(images);
        }, threadPoolExecutor);

        // 异步获取当前商品的秒杀信息
        CompletableFuture<Void> skuSeckillInfoFuture = CompletableFuture.runAsync(() -> {
            // 查询当前商品sku的秒杀优惠信息
            R skuSeckillInfoR = seckillFeignService.getSkuSeckillInfo(skuId);
            if (skuSeckillInfoR.getCode() == 0) {
                SeckillSkuInfoVO data = skuSeckillInfoR.getData(new TypeReference<SeckillSkuInfoVO>() {
                });
                // 保存商品秒杀信息
                skuItemVo.setSeckillSkuInfoVO(data);
            }
        }, threadPoolExecutor);

        //阻塞等待所有任务都完成，再返回 skuItemVo
        CompletableFuture.allOf(saleAttrFuture, spuInfoDescFuture, groupAttrsFuture, imageFuture, skuSeckillInfoFuture).get();
        return skuItemVo;
    }

    @Override
    public SpuInfoEntity getSpuInfoBySkuId(Long skuId) {

        // 获取sku信息
        SkuInfoEntity skuInfoEntity = skuInfoService.getById(skuId);
        Long spuId = skuInfoEntity.getSpuId();


        // 获取spu信息
        SpuInfoEntity byId = spuInfoService.getById(spuId);
        return byId;
    }
}
